package drds.global_transaction.resource_manager;

import drds.global_transaction.resource_manager.undolog.UndoLog;
import lombok.Getter;
import lombok.NonNull;
import lombok.Setter;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ConnectionContext
{
	@Setter
	@Getter
	private String globalTransactionIdWithAddressAndPort;
	@Setter
	@Getter
	private Long branchTransactionId;
	//
	@Setter
	@Getter
	private List<String> lockRecordIdsStringList = new ArrayList<>();
	@Setter
	@Getter
	private List<UndoLog> undoLogList = new ArrayList<>();

	//
	public void addLockRecordIdsString(String lockRecordIdsString)
	{
		lockRecordIdsStringList.add(lockRecordIdsString);
	}

	//
	public void addUndoLog(UndoLog undoLog)
	{
		undoLogList.add(undoLog);
	}

	//
	public void bind(@NonNull String globalTransactionIdWithAddressAndPort)
	{
		if (!inGlobalTransaction())
		{
			setGlobalTransactionIdWithAddressAndPort(globalTransactionIdWithAddressAndPort);
		} else
		{
			if (!this.globalTransactionIdWithAddressAndPort.equals(globalTransactionIdWithAddressAndPort))
			{
				throw new IllegalStateException("当前的全局事务ID已经设置了,传入的值和当前不匹配");
			}
		}
	}

	public String buildLockRecordId()
	{
		if (lockRecordIdsStringList.isEmpty())
		{
			return null;
		}
		StringBuilder sb = new StringBuilder();
		Iterator<String> iterator = lockRecordIdsStringList.iterator();
		while (iterator.hasNext())
		{
			sb.append(iterator.next());
			if (iterator.hasNext())
			{
				sb.append(";");
			}
		}
		return sb.toString();
	}

	public boolean hasUndoLog()
	{
		return undoLogList.size() > 0;
	}

	public boolean inGlobalTransaction()
	{
		return globalTransactionIdWithAddressAndPort != null;
	}

	public boolean isBranchRegistered()
	{
		return branchTransactionId != null;
	}

	public void reset()
	{
		globalTransactionIdWithAddressAndPort = null;
		branchTransactionId = null;
		lockRecordIdsStringList.clear();
		undoLogList.clear();
	}

}
